﻿<?php
/*
 +--------------------------------------------------------------------------
 |   phpBIZ v m2.1  full version
 |   ========================================
 |   by taft@wjl.cn yejun@wjl.cn
 |   http://www.phpbiz.cn http://www.wjl.cn
 |   all rights reserved
 +---------------------------------------------------------------------------
 |
 |   > 最后修改日期：2005-4-30 2006-2-8
 |
 +--------------------------------------------------------------------------
*/
!class_exists('Debug') && exit('Forbidden');
class biz_smarty extends Smarty
{
	
  var $allow_unicode = 1;
  var $get_magic_quotes = 0;
  var $base_url ="";
  var $session_id="";
  var $session_type;
  var $seller =array();
  var $location =0;
  var $nav_link= array();
  var $cache_id;

  function biz_smarty()
  { 
    global $CONF,$_SERVER;
    $this ->Smarty();
	
    $this->debugging = $CONF['smarty_debug'];
    $this->caching = $CONF['smarty_cache'];
    if( $CONF['smarty_cache'] )$this -> cache_lifetime = intval( $CONF['smarty_cache_time'] );
		
    $sk = $CONF[template]?$CONF[template]:"skin1";
    $this -> template_dir = "./templates/".$sk; 
    $this -> config_dir = $this -> template_dir;
    if( !is_dir($this->compile_dir) && !file_exists($this->compile_dir) )
      @mkdir($this->compile_dir);
 
    if( !is_writable($this->compile_dir) || !is_dir($this->compile_dir) )
      { 
	echo "FATAL ERROR: Can't write template cache in the directory: <b>".$this->compile_dir."</b>.<br>Please check if it exists, and have writable permissions.";
	exit;
      }
       
    $this->assign('html_title',$CONF['biz_name']);
    $this -> cache_id = md5($_SERVER['REQUEST_URI']);   // store for cacahing ID

    $this->get_magic_quotes = get_magic_quotes_gpc();
        
    $this -> nav_link[] = array($CONF['biz_name'],"index.php");
	
  }

  function output($template,$cache_flag=false,$private_id=0)
  {
    global $CONF,$INCOME,$DB,$Debug,$ID;
    $query_cnt = $DB -> query_cnt;

    $ex_time     = sprintf( "%.4f",$Debug->endTimer() );

    $cache       = ($this -> caching)? "启用页面缓存 : {$CONF[smarty_cache_time]} 秒":"禁止页面缓存";
		
    //+----------------------------------------------
        
    if ($CONF['debug_level'] > 0)
      {
        
	$stats = "<br clear='all' />\n<br />\n<div align='center'>[ 程序执行时间： $ex_time 秒 ] &nbsp; [ 数据库查询： $query_cnt 次 ] &nbsp; [ $cache ]</div>\n<br />";
      }
        		  
    //+----------------------------------------------
        		  
    if ($CONF['debug_level'] >= 2)
      {
	$stats .= "<br />\n<div class='tableborder'>\n<div class='pformstrip'>FORM and GET Input</div><div class='row1' style='padding:6px'>\n";
        
	while( list($k, $v) = each($INCOME) )
	  {
	    $stats .= "<strong>$k</strong> = $v<br />\n";
	  }
			
	$stats .= "</div>\n</div>";
        
      }

    //+----------------------------------------------
    if ($CONF['debug_level'] >= 3)
      {
	$stats .= "<br />\n<div class='tableborder'>\n<div class='pformstrip'>Queries Used</div><div class='row1' style='padding:6px'>";
       					
	foreach($DB->query_cache as $q)
	  {
	    $q = htmlspecialchars($q);
	    $q = preg_replace( "/^SELECT/i" , "<span class='red'>SELECT</span>"   , $q );
	    $q = preg_replace( "/^UPDATE/i" , "<span class='blue'>UPDATE</span>"  , $q );
	    $q = preg_replace( "/^DELETE/i" , "<span class='orange'>DELETE</span>", $q );
	    $q = preg_replace( "/^INSERT/i" , "<span class='green'>INSERT</span>" , $q );
	    $q = str_replace( "LEFT JOIN"   , "<span class='red'>LEFT JOIN</span>" , $q );
        		
	    $q = preg_replace( "/(".$CONF['sql_tbl_prefix'].")(\S+?)([\s\.,]|$)/", "<span class='purple'>\\1\\2</span>\\3", $q );
        			
	    $stats .= "$q<hr />\n";
	  }
        	
	$stats .= "</div>\n</div>";
      }
		
    $this -> assign("beianCode", $CONF[beianCode]);
    $this -> do_nav_link();
    $this -> assign("stats",$stats);   // too simply, but ok right now!
		
    if($cache_flag)
      {  
	// wanna cache
	$this -> display($template,$private_id,$this->cache_id);
      }else
      {   
	$this -> caching = false;
	$this -> display($template);
      }
    //echo $ex_time     = sprintf( "%.4f",$Debug->endTimer() );
    //echo " sql:".$query_cnt;
    exit;
		
  }

  /*-------------------------------------------------------------------------*/
  // Makes incoming info "safe"              
  /*-------------------------------------------------------------------------*/
    
  function parse_incoming()
  {
    global $_GET, $_POST, $REQUEST_METHOD, $REMOTE_ADDR, $HTTP_PROXY_USER, $HTTP_X_FORWARDED_FOR;
    $return = array();
	
    if( is_array($_GET) )
      {
	while( list($k, $v) = each($_GET) )
	  {
	    if( is_array($_GET[$k]) )
	      {
		while( list($k2, $v2) = each($_GET[$k]) )
		  {
		    $return[$k][ $this->clean_key($k2) ] = $this->clean_value($v2);
		  }
	      }
	    else
	      {
		$return[$k] = $this->clean_value($v);
	      }
	  }
      }
		
    // Overwrite GET data with post data
		
    if( is_array($_POST) )
      {
	while( list($k, $v) = each($_POST) )
	  {
	    if ( is_array($_POST[$k]) )
	      {
		while( list($k2, $v2) = each($_POST[$k]) )
		  {
		    $return[$k][ $this->clean_key($k2) ] = $this->clean_value($v2);
		  }
	      }
	    else
	      {
		$return[$k] = $this->clean_value($v);
	      }
	  }
      }
		
    //----------------------------------------
    // Sort out the accessing IP
    // (Thanks to Cosmos and schickb)
    //----------------------------------------
		
    $addrs = array();
		
    foreach( array_reverse( explode( ',', $HTTP_X_FORWARDED_FOR ) ) as $x_f )
      {
	$x_f = trim($x_f);
			
	if ( preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $x_f ) )
	  {
	    $addrs[] = $x_f;
	  }
      }
		
    $addrs[] = $_SERVER['REMOTE_ADDR'];
    $addrs[] = $HTTP_PROXY_USER;
    $addrs[] = $REMOTE_ADDR;
		
    //header("Content-type: text/plain"); print_r($addrs); print $_SERVER['HTTP_X_FORWARDED_FOR']; exit();
		
    $return['IP_ADDRESS'] = $this->select_var( $addrs );
												 
    // Make sure we take a valid IP address
		
    $return['IP_ADDRESS'] = preg_replace( "/^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/", "\\1.\\2.\\3.\\4", $return['IP_ADDRESS'] );
		
    $return['request_method'] = ( $_SERVER['REQUEST_METHOD'] != "" ) ? strtolower($_SERVER['REQUEST_METHOD']) : strtolower($REQUEST_METHOD);
		
    return $return;
  }
	
  /*-------------------------------------------------------------------------*/
  // Key Cleaner - ensures no funny business with form elements             
  /*-------------------------------------------------------------------------*/
    
  function clean_key($key)
  {
    
    if ($key == "")
      {
	return "";
      }
    $key = preg_replace( "/\.\./"           , ""  , $key );
    $key = preg_replace( "/\_\_(.+?)\_\_/"  , ""  , $key );
    $key = preg_replace( "/^([\w\.\-\_]+)$/", "$1", $key );
    return $key;
  }
    
  function clean_value($val)
  {
    	
    if ($val == "")
      {
	return "";
      }
    	
    $val = str_replace( "&#032;", " ", $val );
     	
    $val = str_replace( "&"            , "&amp;"         , $val );
    $val = str_replace( "<!--"         , "&#60;&#33;--"  , $val );
    $val = str_replace( "-->"          , "--&#62;"       , $val );
    $val = preg_replace( "/<script/i"  , "&#60;script"   , $val );
    $val = str_replace( ">"            , "&gt;"          , $val );
    $val = str_replace( "<"            , "&lt;"          , $val );
    $val = str_replace( "\""           , "&quot;"        , $val );
    //$val = preg_replace( "/\n/"        , "<br>"          , $val ); // Convert literal newlines
    $val = preg_replace( "/\\\$/"      , "&#036;"        , $val );
    //$val = preg_replace( "/\r/"        , ""              , $val ); // Remove literal carriage returns
    $val = str_replace( "!"            , "&#33;"         , $val );
    $val = str_replace( "'"            , "&#39;"         , $val ); // IMPORTANT: It helps to increase sql query safety.
    	
    // Ensure unicode chars are OK
    	
    if ( $this->allow_unicode )
      {
	$val = preg_replace("/&amp;#([0-9]+);/s", "&#\\1;", $val );
      }
		
    // Strip slashes if not already done so.
		
    if ( $this->get_magic_quotes )
      {
	$val = stripslashes($val);
      }
    	
    // Swop user inputted backslashes
    	
    $val = preg_replace( "/\\\(?!&amp;#|\?#)/", "&#092;", $val ); 
    	
    return $val;
  }

  /*-------------------------------------------------------------------------*/
  // Variable chooser             
  /*-------------------------------------------------------------------------*/
    
  function select_var($array)
  {
    	
    if ( !is_array($array) ) return -1;
    	
    ksort($array);
    	    	
    $chosen = -1;  // Ensure that we return zero if nothing else is available
    	
    foreach ($array as $k => $v)
      {
	if (isset($v))
	  {
	    $chosen = $v;
	    break;
	  }
      }
    	
    return $chosen;
  }

  function error( $msg = "未知错误" , $url="" )
  {
    $this -> assign("msg_info",$msg);
    if($url!="")
      $url = ROOT_PATH."index.php".$url;
    $this -> assign("back_url",$url);
    $this -> output("Error.tpl");
  }

  /*------------------------------------------------------------------------*/
  // txt_stripslashes
  // ------------------
  // Make Big5 safe - only strip if not already...
  /*-------------------------------------------------------------------------*/
	
  function txt_stripslashes($t)
  {
    if ( $this->get_magic_quotes )
      {
	$t = stripslashes($t);
      }
    	
    return $t;
  }

  /*-------------------------------------------------------------------------*/
  // Sets a cookie, abstract layer allows us to do some checking, etc                
  /*-------------------------------------------------------------------------*/    
    
  function my_setcookie($name, $value = "", $sticky = 1) 
  {
    global $CONF;
        
    //$expires = "";
        
    if ($sticky == 1)
      {
	$expires = time() + 60*60*24*365;
      }

    $CONF['cookie_domain'] = $CONF['cookie_domain'] == "" ? ""  : $CONF['cookie_domain'];
    $CONF['cookie_path']   = $CONF['cookie_path']   == "" ? "/" : $CONF['cookie_path'];
        
    $name = $CONF['cookie_id'].$name;
      
    setcookie($name, $value, $expires, $CONF['cookie_path'], $CONF['cookie_domain']);
  }
    
  /*-------------------------------------------------------------------------*/
  // Cookies, cookies everywhere and not a byte to eat.                
  /*-------------------------------------------------------------------------*/  
    
  function my_getcookie($name)
  {
    global $CONF, $_COOKIE;
    	
    if (isset($_COOKIE[$CONF['cookie_id'].$name]))
      {
	return urldecode($_COOKIE[$CONF['cookie_id'].$name]);
      }
    else
      {
	return FALSE;
      }
    	
  }
  /*-------------------------------------------------------------------------*/
  // Delete buck of picture files on the server
  // make sure "buck of" means array!
  /*-------------------------------------------------------------------------*/
  function unlink_pic($file_name,$thumb=0 )
  {
    if( !is_array($file_name) ) return;
    foreach( $file_name as $v )
      {
	unlink( $this->make_full_path($v,$thumb) );
      }
    return;
  }
  function make_full_path($file_name,$thumb=0)
  {
    global $CONF;
    if($CONF['single_upload_dir']==0)
      {
	$start = 5;
	if($thumb) $start += strlen($CONF['thumb_prefix']);
	$timestamp= substr($file_name,$start,10); 
	$timestamp = intval($timestamp);  // fix bug with php5
	return $CONF['upload_url'].date("Y",$timestamp)."/".date("m",$timestamp)."/".$file_name;
      }else{
      return ROOT_PATH.$CONF['upload_url'].$file_name;
    }
  }

  function get_thumb($file_name)
  {
    global $CONF;

    $pathfile = $this -> make_full_path($file_name);
    $thumbfile= $this -> make_full_path($CONF['thumb_prefix'].$file_name,1);
    if(!@is_file($thumbfile))
      {
	$this -> _resize($thumbfile,$pathfile,"php","");
      }
    return $thumbfile;
  }

  function redirect( $url )
  {
    header("Location:$url");
    exit;
  }
  function build_pagelinks($data)
  {

    $work = array();
		
    $section = ($data['leave_out'] == "") ? 2 : $data['leave_out'];  // Number of pages to show per section( either side of current), IE: 1 ... 4 5 [6] 7 8 ... 10
	
    $work['pages']  = 1;
		
    if ( ($data['TOTAL_POSS'] % $data['PER_PAGE']) == 0 )
      {
	$work['pages'] = $data['TOTAL_POSS'] / $data['PER_PAGE'];
      }
    else
      {
	$number = ($data['TOTAL_POSS'] / $data['PER_PAGE']);
	$work['pages'] = ceil( $number);
      }        //分多少页
		
		
    $work['total_page']   = $work['pages'];
    $work['current_page'] = $data['CUR_ST_VAL'] > 0 ? ($data['CUR_ST_VAL'] / $data['PER_PAGE']) + 1 : 1;
		
	
    if ($work['pages'] > 1)
      {
	$work['first_page'] = "分页：";
			
	for( $i = 0; $i <= $work['pages'] - 1; ++$i )
	  {
	    $RealNo = $i * $data['PER_PAGE'];
	    $PageNo = $i+1;
				
	    if ($RealNo == $data['CUR_ST_VAL'])
	      {
		$work['page_span'] .= "&nbsp;<b>[{$PageNo}]</b>";
	      }
	    else
	      {
					
		if ($PageNo < ($work['current_page'] - $section))
		  {
		    $work['st_dots'] = "&nbsp;<a href='{$data['BASE_URL']}&amp;st=0' title='首页'} 1'>&laquo; 首页</a>&nbsp;...";
		    continue;
		  }
					
		// If the next page is out of our section range, add some dotty dots!
					
		if ($PageNo > ($work['current_page'] + $section))
		  {
		    $work['end_dots'] = "...&nbsp;<a href='{$data['BASE_URL']}&amp;st=".($work['pages']-1) * $data['PER_PAGE']."' title='总页数 {$work['pages']}'>末页 &raquo;</a>";
		    break;
		  }
					
					
		$work['page_span'] .= "&nbsp;<a href='{$data['BASE_URL']}&amp;st={$RealNo}'>{$PageNo}</a>";
	      }
	  }
			
	$work['return']    = $work['first_page'].$work['st_dots'].$work['page_span'].'&nbsp;'.$work['end_dots'];
      }
    else
      {
	$work['return']    = $data['L_SINGLE'];
      }
	
    return $work['return'];
  }
	
  function do_nav_link( )
  {
    foreach( $this->nav_link as $k => $v )
      {
	if( !$k )
	  {
	    $link_str="<a href='{$this->nav_link[$k][1]}' class='contentgrey'>".$this->nav_link[$k][0]."</a>";
	  }
	else
	  {
	    if($this->nav_link[$k][1])
	      {
		$link_str.=" -><a href='{$this->nav_link[$k][1]}' class='contentgrey'>".$this->nav_link[$k][0]."</a>";
	      }else{
	      $link_str.=" ->".$this->nav_link[$k][0];
	    }
	  }
      }
    $this -> assign("nav_link",$link_str);

  }

  function _do_headers()
  {
    return;
  }
	
  //-------------------------------------------
  // print a pure redirect screen
  //-------------------------------------------
    
  function redirect_screen($text="", $url="", $override=0)
  {
         
    global $CONF,$DB;
        
    if ( $override != 1 )
      {
	if ( $CONF['biz_url'])
	  {
	    $url = $CONF['biz_url']."index.php".$url;
	  }
	else
	  {
	    $url = "{$CONF['biz_url']}index.php".$url;
	  }
      }
    $this -> assign("content",$text);
    $this -> assign("url",$url);
    $this -> caching = false;   // not cache 2006-2-3
    $htm = $this->fetch("Refresh.tpl");
    	
    //$DB->close_db();
		
    echo $htm;
    exit;
  }

  //----------------- Add by 缩图 --------------------------- 
  function _resize($dest,$src,$imglib,$convert_path){ 
        
    if(!@is_file($src)) return;
	   
    $quality=82;  //----JPG 
        
    $image_info=getimagesize($src); 
    $srcSize_W=$image_info[0]; 
    $srcSize_H=$image_info[1]; 
        
    $img_aspect=$srcSize_W/$srcSize_H; 
        
    if( $srcSize_H > $srcSize_W*2 ) define(SMALL_IMAGE_HEIGHT,100);

    if(SMALL_IMAGE_WIDTH>0){
      $destSize_W=SMALL_IMAGE_WIDTH; 
      $destSize_H=intval($destSize_W/$img_aspect); 
    }else if(SMALL_IMAGE_HEIGHT>0){
      $destSize_H=SMALL_IMAGE_HEIGHT; 
      $destSize_W=intval($destSize_H*$img_aspect); 
    }else{
      $destSize_W=100; 
      $destSize_H=intval($destSize_W/$img_aspect);
    }       
     
    if($imglib=="php") { 
      //----------- With buildin php GD function -----------------------           
            
      $destImage = @imageCreateTrueColor($destSize_W,$destSize_H); 
           
      //imageAntiAlias($destImage,true); 
      //------消鋸齒演算，因看不出效果，故移除以節省時間。 
                       
      switch ($image_info[2]) 
	{ 
	case 1: //GIF 
	  $srcImage = @imageCreateFromGif($src);  
	  imageCopyResampled($destImage, $srcImage, 0, 0, 0, 0,$destSize_W,$destSize_H,$srcSize_W,$srcSize_H); 
	  @imagegif($destImage,$dest); 
	  //@copy ($src,$dest); 
	  break; 
                   
	case 2: //JPEG 
	  $srcImage = @imageCreateFromJpeg($src); 
	  //------- 進行縮圖演算--------------- 
	  imageCopyResampled($destImage, $srcImage, 0, 0, 0, 0,$destSize_W,$destSize_H,$srcSize_W,$srcSize_H); 
	  @imageJpeg($destImage,$dest,$quality); 
	  break; 
                   
	case 3: //PNG 
	  $srcImage = imageCreateFromPng($src); 
	  //------- 進行縮圖演算--------------- 
	  imageCopyResampled($destImage, $srcImage, 0, 0, 0, 0,$destSize_W,$destSize_H,$srcSize_W,$srcSize_H); 
	  imagePng($destImage,$dest);  
	  break; 
                   
	default: 
	  return false; 
	  break; 
	} 
      if($srcImage)  imagedestroy($srcImage); 
      if($destImage) imagedestroy($destImage);      
                 
    }else{ 
      @copy ($src,$dest); 
    } 
      
  }
	 
  function pool_refresh()
  {
    global $DB,$POSTER;
		 
    $tm = time();
    //清除过期商铺
    $DB -> db_query("DELETE FROM biz_order_pool WHERE end_time<".time()." AND active = 1");

    //更新首页商品
    $DB -> db_query("SELECT * FROM biz_order_pool WHERE goods_id IS NOT NULL AND active = 1 AND type = {$POSTER[index_goods][type]}");
    $active_num = $DB -> db_fetch_num();
    if(  $up = $POSTER[index_goods][num]-$active_num )
      {
	$DB -> db_query( "UPDATE biz_order_pool SET end_time = end_time + $tm + order_length*24*3600,active = 1 WHERE active = 0 AND type = {$POSTER[index_goods][type]} AND shop_id IS NULL ORDER BY id LIMIT ".$up );
      }
    //更新竟价商品
    $DB -> db_query("SELECT * FROM biz_order_pool WHERE goods_id IS NOT NULL AND active = 1 AND type = {$POSTER[bid_goods][type]}");
    $active_num = $DB -> db_fetch_num();
    if(  $up = $POSTER[bid_goods][num]-$active_num )
      {
	$DB -> db_query( "UPDATE biz_order_pool SET end_time = end_time + $tm + order_length*24*3600,active = 1 WHERE active = 0 AND type = {$POSTER[bid_goods][type]} AND shop_id IS NULL ORDER BY id LIMIT ".$up );
      }
    //更新首页商铺
    $DB -> db_query("SELECT * FROM biz_order_pool WHERE shop_id IS NOT NULL AND active = 1 AND type=".$POSTER[index_shop][type]);
    $active_num = $DB -> db_fetch_num();
    if(  $up = $POSTER[index_shop][num]-$active_num )
      {
	$DB -> db_query( "UPDATE biz_order_pool SET end_time =  end_time + $tm + order_length*24*3600,active = 1 WHERE active = 0 AND type=".$POSTER[index_shop][type]." AND goods_id IS NULL ORDER BY id LIMIT ".$up );
      }
    //更新二级商铺
    $DB -> db_query("SELECT * FROM biz_order_pool WHERE shop_id IS NOT NULL AND active = 1 AND type=".$POSTER[second_shop][type]);
    $active_num = $DB -> db_fetch_num();
    if(  $up = $POSTER[second_shop][num]-$active_num )
      {
	$DB -> db_query( "UPDATE biz_order_pool SET end_time = end_time + $tm + order_length*24*3600,active = 1 WHERE active = 0 AND type=".$POSTER[second_shop][type]." AND goods_id IS NULL ORDER BY id LIMIT ".$up );
      }
  }

  function update_repute($item) 
  {
    global $DB,$reputedb;
    if(empty($reputedb[$item]) || $reputedb[$item]==0 ) $reputedb[$item] = 0;
    $DB->db_query("UPDATE biz_seller_data SET repute = repute +".$reputedb[$item]." WHERE seller_id='".$this->seller['seller_id']."'");
    return;
  }
}

class  session
{
  var $ip_address;
  var $time_now;
  var $session_user_id;
  var $session_id;
  var $session_dead_id;
  var $location;
  var $seller=array();
	
  function authorise()
  {
    global $BIZ,$INCOME;

    //--------------------------------------------
    //  ip banned check 
    //--------------------------------------------

    //--------------------------------------------

    $this->ip_address = $INCOME['IP_ADDRESS'];
    $this->time_now   = time();

    $cookie = array();
    $cookie['session_id']   = $BIZ->my_getcookie('session_id');
    $cookie['seller_id']    = $BIZ->my_getcookie('seller_id');
    $cookie['pass_hash']    = $BIZ->my_getcookie('pass_hash');

    if ( $cookie['session_id'] )
      {	
	$this->get_session($cookie['session_id']);
	$BIZ->session_type = 'cookie';
      }
    elseif ( $INCOME['s'] )
      {
	$this->get_session($INCOME['s']);
	$BIZ->session_type = 'url';
      }
    else
      {
	$this->session_id = 0;
      }
    //-------------------------------------------------								  
    // Do we have a valid session ID?
    //-------------------------------------------------
    if ( $this->session_id )
      {   
	// BREAKPOINT
	//			print_r($_COOKIE);
	//			die();
	// We've checked the IP addy and browser, so we can assume that this is
	// a valid session.
	if ( ($this->session_user_id != 0) and ( ! empty($this->session_user_id) ) )
	  {
	    // It's a seller session, so load the seller.

	    $this->load_seller($this->session_user_id);
	    // Did we get a seller?
				
	    if ( (! $this->seller['seller_id']) or ($this->seller['seller_id'] == 0) )
	      {
		$this->unload_seller();
		$this->update_guest_session();
	      }
	    else
	      {   
		$this->update_seller_session();
	      }
	  }
	else
	  {  
	    $this->update_guest_session();
	  }
		
      }
    else
      {
	// We didn't have a session, or the session didn't validate
			
	// Do we have cookies stored?
			
	if ($cookie['seller_id'] != "" and $cookie['pass_hash'] != "")
	  {
	    $this->load_seller($cookie['seller_id']);
				
	    if ( (! $this->seller['seller_id']) or ($this->seller['seller_id'] == 0) )
	      {
		$this->unload_seller();
		$this->create_guest_session();
	      }
	    else
	      {
		if ($this->seller['seller_password'] == $cookie['pass_hash'])
		  {
		    $this->create_seller_session();
		  }
		else
		  {
		    $this->unload_seller();
		    $this->create_guest_session();
		  }
	      }
	  }
	else
	  {
	    $this->create_guest_session();
	  }
      }

    //-------------------------------------------------
    // Set a session ID cookie
    //-------------------------------------------------
    $BIZ->my_setcookie("session_id", $this->session_id, -1);

    return $this->seller;

  }
	
  function load_seller($seller_id=0)
  {
    global $DB, $BIZ, $INCOME;
    	
    $seller_id = intval($seller_id);
    	
    if ($seller_id != 0)
      {
            				  
	$DB->db_query("SELECT * FROM biz_seller  WHERE seller_id='$seller_id'");
            
	if ( $DB->db_fetch_num() )
	  {   
	    $this->seller = $DB->db_fetch_row();
	  }
            
	//-------------------------------------------------
	// Unless they have a seller id, log 'em in as a guest
	//-------------------------------------------------
            
	if ( ($this->seller['seller_id'] == 0) or (empty($this->seller['seller_id'])) )
	  {
	    $this->unload_seller();
	  }
      }
		
    unset($seller_id);
  }

  //+-------------------------------------------------
  // Remove the users cookies
  //+-------------------------------------------------
	
  function unload_seller()
  {
    global $DB, $BIZ, $INCOME;
		
    // Boink the cookies
		
    $BIZ->my_setcookie( "seller_id" , "0", -1  );
    $BIZ->my_setcookie( "pass_hash" , "0", -1  );
		
    $this->seller['seller_id']       = 0;
    $this->seller['seller_logaccount']     = "";
    $this->seller['seller_password'] = "";
		
  }
    
  //-------------------------------------------
  // Updates a current session.
  //-------------------------------------------
    
  function update_seller_session() 
  {
    global $DB,$INCOME;
        
    // Make sure we have a session id.
        
    if ( ! $this->session_id )
      {
	$this->create_seller_session();
	return;
      }
        
    if (empty($this->seller['seller_id']))
      {
	$this->unload_seller();
	$this->create_guest_session();
	return;
      }
                				
    $db_str = $DB->db_compile_update_fields(
					    array(
						  'seller_logaccount'  => $this->seller['seller_logaccount'],
						  'seller_id'    => intval($this->seller['seller_id']),
						  'running_time' => $this->time_now,
						  'location'     => $INCOME['act'].",".$INCOME['p'].",".$INCOME['code']
						  )
					    );
											  
    $DB->db_query("UPDATE biz_session SET $db_str WHERE id='{$this->session_id}'" );
        
  }        
    
  //--------------------------------------------------------------------

  function update_guest_session()
  {
    global $DB, $BIZ, $INCOME;
        
    // Make sure we have a session id.
        
    if ( ! $this->session_id )
      {
	$this->create_guest_session();
	return;
      }
        
    $query  = "UPDATE biz_session SET seller_logaccount='',seller_id='0' ";
    $query .= ", running_time='".$this->time_now."', location='".$INCOME['act'].",".$INCOME['code']."' ";
    $query .= "WHERE id='".$this->session_id."'";
        
    // Update the database
        
    $DB->db_query( $query );
  } 
                    
    
  //-------------------------------------------
  // Get a session based on the current session ID
  //-------------------------------------------
    
  function get_session($session_id="")
  {
    global $DB, $CONF, $BIZ;

    $result = array();
        
    $query = "";
        
    $session_id = preg_replace("/([^a-zA-Z0-9])/", "", $session_id);
        
    if ( $session_id )
      {
        
	$DB->db_query("SELECT id, seller_id, running_time, location FROM biz_session WHERE id='".$session_id."' and ip_address='".$this->ip_address."'".$query );

	if ( $DB->db_fetch_num() != 1 )
	  {
	    // Either there is no session, or we have more than one session..
				
	    $this->session_dead_id   = $session_id;
	    $this->session_id        = 0;
	    $this->session_user_id   = 0;
	    return;
	  }
	else
	  {
	    $result = $DB->db_fetch_row();
				
	    if ($result['id'] == "")
	      {
		$this->session_dead_id   = $session_id;
		$this->session_id        = 0;
		$this->session_user_id   = 0;
		unset($result);
		return;
	      }
	    else
	      {   
		$this->session_id        = $result['id'];
		$this->session_user_id   = $result['seller_id'];
		$this->last_click        = $result['running_time'];
		$this->location          = $result['location'];
		unset($result);
		return;
	      }
	  }
      }
  }

  //-------------------------------------------
  // Creates a seller session.
  //-------------------------------------------
    
  function create_seller_session()
  {
    global $DB, $CONF, $BIZ, $INCOME;
        
    if ($this->seller['seller_id'])
      {
	//---------------------------------
	// Remove the defunct sessions
	//---------------------------------
        	
	$CONF['session_expiration'] = $CONF['session_expiration'] ? (time() - $CONF['session_expiration']) : (time() - 3600);
			
	$DB->db_query( "DELETE FROM biz_session WHERE running_time < {$CONF['session_expiration']} or seller_id='".$this->seller['seller_id']."'");
			
	$this->session_id  = md5( uniqid(microtime()) );
			
	//---------------------------------
	// Insert the new session
	//---------------------------------
        	
	$DB->db_query("INSERT INTO biz_session (id, seller_logaccount, seller_id, ip_address,running_time, location) ".
		      "VALUES ('".$this->session_id."', '".$this->seller['seller_logaccount']."', '".$this->seller['seller_id']."', '".$this->ip_address."', '".$this->time_now."',''".
		      ")"  );
	/// for debug
      }
    else
      {
	$this->create_guest_session();
      }
  }
    
  //--------------------------------------------------------------------
    
  function create_guest_session() 
  {
    global $DB, $CONF, $BIZ;
        
    //---------------------------------
    // Remove the defunct sessions
    //---------------------------------
		
    if ( ($this->session_dead_id != 0) and ( ! empty($this->session_dead_id) ) )
      {
	$extra = " or id='".$this->session_dead_id."'";
      }
    else
      {
	$extra = "";
      }
		
    $CONF['session_expiration'] = $CONF['session_expiration'] ? (time() - $CONF['session_expiration']) : (time() - 3600);
		
    $DB->db_query( "DELETE FROM biz_session WHERE running_time < {$CONF['session_expiration']} or ip_address='".$this->ip_address."'".$extra);
		
    $this->session_id  = md5( uniqid(microtime()) );
		
    //---------------------------------
    // Insert the new session
    //---------------------------------
		
    $DB->db_query("INSERT INTO biz_session (id, seller_logaccount, seller_id, ip_address, running_time, location) ".
		  "VALUES ('".$this->session_id."', '', '0', '".$this->ip_address."', '".$this->time_now."', '' ".")"   );
					   
  }
}

class manager
{
  var $_property_name;
  var $_property_id;
  var $_goods_valid_day;   //public
  var $_goods_total;
  var $_shop_total;
  var $_order_allow_count;
  var $_money_total;
  var $_credit;
  var $_allow_goods;
  var $_allow_shop;
  var $_seller_id;
  var $_end_time;
  var $_fee;
  var $_init_fee;
  var $_action;
  var $_reputate;
  var $_rank_id;
  var $_global_allow_pic;

  function manager($seller_id)
  {
    if(!$seller_id) return;
    $this -> _seller_id = $seller_id;
  }
	
  function load_property()
  {
    global $DB;

    $DB-> db_query("SELECT * FROM biz_seller_data WHERE seller_id =". $this -> _seller_id);
		$data = $DB-> db_fetch_row();
		$this -> _goods_total = $data['goods_total'];
		$this -> _shop_total = $data['shop_total'];
		$this -> _money_total = $data['money'];
		$this -> _credit = $data['credit'];
		$this -> _property_id = $data['property_id'];
		$this -> _end_time = $data['end_time'];
		$this -> _reputate = $data['repute'];
		$this -> _allow_att_pic_total = $data['pic_allow'];
		
		$DB -> db_query("SELECT * FROM biz_seller_property WHERE level_id = $data[property_id]");
		$data = $DB -> db_fetch_row();
		$this -> _allow_goods = $data['goods_total'];
		$this -> _allow_shop = $data['shop_total'];
		$this -> _property_name = $data['property_name'];
		$this -> _order_allow_count = $data['order_allow_count'];		
		$this -> _goods_valid_day = $data['goods_valid_day'];
		$this -> _fee=$data['fee'];
		$this -> _init_fee=$data['free_money'];
		$this -> _action = unserialize($data['action']);
		$this -> _rank_id = $data['rank_id'];
		$this -> _global_allow_pic = $data['att_pic_total'];

		return;
	}
	function get_valid_day()
	{
          $this -> load_property();
          return $this->_goods_valid_day;
	}
    
	function check_property($action)
	{
		switch($action)
		{
			case 'goodst':
				if($this -> _goods_total >=$this -> _allow_goods) return false; else return true;
			    break;
			case 'shopt':
			    if($this -> _shop_total >= $this -> _allow_shop) return false; else return true;
			    break;
		}

		return;
	}
	function get_seller_data($str)
	{
		global $DB;
		$data = array();
		$str_array=explode(",",$str);
		if(!count($str_array)) return false;
		$DB -> db_query("SELECT ".$str." FROM biz_seller_data WHERE seller_id=".$this->_seller_id." LIMIT 1");
		$r = $DB -> db_fetch_row();
		foreach($str_array as $v)
		{
			$data[$v]=$r[$v];
		}
		return $data;
	}
	function get_order_count()
	{
		$this -> load_property();
		return $this -> _order_allow_count;
	}
	function get_level()
	{
		$this -> load_property();
		return $this -> _property_id;
	}
	function get_rank()
	{
		$this -> load_property();
		return $this -> _rank_id;
	}
	function get_buy_pic()
	{
		$this -> load_property();
		return ($this->_allow_att_pic_total)-($this -> _global_allow_pic);
	}

	function get_end_time()
	{
		$this -> load_property();
		return $this ->_end_time;
	}
	function init_fee()  //赠送启动资金
	{
		global $DB,$BIZ;
        $this -> load_property();
		$timestamp=time();
		$DB -> db_query("INSERT INTO biz_charge_log ( `seller_logaccount` , `operator` , `time` , `money`,`sid` ) VALUES ( '{$BIZ->seller[seller_logaccount]}', '', '{$timestamp}', '{$this->_init_fee}','{$this->_seller_id}')");
		$DB -> db_query("UPDATE biz_seller_data SET money=money+".$this->_init_fee." WHERE seller_id=".$this->_seller_id);
       if($DB->db_affected_rows()==1) return true;
	   else return false;
	}
	function get_level_name()
	{
		$this -> load_property();
		return $this -> _property_name;
	}
	function update_end_time($tick)  // 计算出等级购买失效日期
	{
	   global $DB;
	   $this -> load_property();
           $endt= time()+$tick;
             
	   $DB -> db_query("UPDATE biz_seller_data SET end_time=".$endt." WHERE seller_id=".$this->_seller_id);
       if($DB->db_affected_rows()==1) return true;
	   else return false;
	}

	function get_money() //用户当前余额
	{
		$this -> load_property();
		return $this->_money_total;
	}
	function get_fee($level_id=0)  //购买级别的费用
	{
		global $DB;
		if($level_id)     //取特定id的fee
		{
			$DB -> db_query("SELECT fee FROM biz_seller_property WHERE level_id=".$level_id." LIMIT 1");
			$r = $DB -> db_fetch_row();
			return $r['fee'];
		}else
		{
			$this -> load_property();
			return $this -> _fee;
		}
	}
	function build_property_info()
	{
		$this -> load_property();
		return sprintf("您目前拥有声望: <font class=red>%d</font>。 <br><br>您目前的等级是:<font class=red>%s</font>，可允许开设<font class=red>%d</font>家店铺，可允许出售<font class=red>%d</font>件商品，招租铺位可续次数<font class=red>%d</font>，拥有上传副图个数<font class=red>%d</font>。",$this->_reputate,$this->_property_name,$this->_allow_shop,$this->_allow_goods,$this->_order_allow_count,$this->_allow_att_pic_total);
	}
	function consume($cost)
	{
		global $DB;
		$this -> load_property();
		$this->_money_total = $this->_money_total - $cost;
		if($this->_money_total <0 ) return $this->_money_total;
		else
		{
		$DB -> db_query("UPDATE biz_seller_data SET money=".$this->_money_total." WHERE seller_id=".$this ->_seller_id);
	    return $this->_money_total;
		}
	}
	function consume_log($cost,$detail,$id)
	{
		global $DB ;
		$tm = time();
		$DB -> db_query( "INSERT INTO `biz_consume_log` ( `seller_id` , `money` , `time` , `act` ) VALUES ('$id', '$cost', '$tm', '$detail')");
	}
	function check($act)
	{
		$this -> load_property();
		$a = $this -> _action;
		if(!$a[$act]) return false;
		else return true;
	}
	function control_panel($msg='')    
	{  // 00 , default
		global $BIZ,$DB;
         
	//------------------------------
	//fill display stuff here
        //------------------------------
        if($msg=='nocharge')
		     $BIZ ->assign("notice","您目前还<font class=blue size=+2>未付费或未被批准</font>，所有功能暂时停止。请点击<a href='?act=User&code=buy'>[<font class=red>这里</font>]</a>付费开通。");
		elseif($msg=='due')
			$BIZ ->assign("notice","您目前购买等级<font class=blue size=+2>已到期</font>，所有功能暂时停止。请点击<a href='?act=User&code=buy'>[<font class=red>这里</font>]</a>续费开通。");

		$DB -> db_query("SELECT count(*) as ct FROM biz_goods WHERE seller_id = ".$BIZ ->seller['seller_id']." AND goods_mark_sell='0' UNION ALL SELECT count(*) as ct FROM biz_shop WHERE seller_id = ".$BIZ ->seller['seller_id']);
		$r_g = $DB -> db_fetch_row();
		$BIZ -> assign("gnum",$r_g['ct']);

		$r_s = $DB -> db_fetch_row();
		$BIZ -> assign("snum",$r_s['ct']);

		$DB -> db_query("SELECT count(*) as ct from biz_message  JOIN biz_goods ON seller_id = ".$BIZ ->seller['seller_id']."  AND message_owner_goods_id = goods_id AND message_reply_content IS NULL");
        $r_m = $DB -> db_fetch_row();
		$BIZ -> assign("mnum",$r_m['ct']);
		//----------------------------------
		//fill recent user property info
		//----------------------------------
		$BIZ -> assign("prop",$this -> build_property_info());
		return;
	}
}
class cache
{
	function DB_Cache($sql)
	{
	    global $DB;
	    $bizdb=array();
	    $query=$DB->db_query($sql);
	    while($rt=$DB->db_fetch_row($query,MYSQL_NUM))
		{
		$bizdb[]=$rt;
		}
	    return $this -> array_export($bizdb);
    }
 
    function array_export($array,$c=1,$t='',$var='')
	{
		$c && $var="array(\r\n";
		$t.="  ";
		if(is_array($array))
		{
		    foreach($array as $key => $value)
		    {
			    $var.="$t'".addslashes($key)."'=>";
			    if(is_array($value))
				{
				    $var.="array(\r\n";
				    $var=$this->array_export($value,0,$t,$var);
				    $var.="$t),\r\n";
			    }else{
				    $var.="'".addslashes($value)."',\r\n";
			    }
		     }
	     }
	     if($c)
	     {
		   $var.=")";
	     }
	return $var;
    }

	function write_cache($filename,$data,$method="rb+",$iflock=1)
	{
		touch($filename);
		$handle=fopen($filename,$method);
		if($iflock)
		{
			flock($handle,LOCK_EX);
		}
		fputs($handle,$data);
		if($method=="rb+") ftruncate($handle,strlen($data));
		fclose($handle);
	}
}

// global function
function substrs($content,$length)
{
	if(strlen($content)>$length){
	$num=0;
	for($i=0;$i<$length-3;$i++) {
		if(ord($content[$i])>127)$num++;
	}
	$num%2==1 ? $content=substr($content,0,$length-4):$content=substr($content,0,$length-3);
	$content.=' ...';
	}
	return $content;
}
function repute_compute($point)
{
	$repute_dimond=0;
	$repute_shell=1;
	 
    $repute_dimond = intval( $point / 5000 );
	$repute_tmp_shell = ($point - $repute_dimond * 5000)/1000 ;
	if($repute_tmp_shell >= 1 ) $repute_shell = intval($repute_tmp_shell);
	if( ($repute_dimond > 0) && $repute_tmp_shell <1 ) $repute_shell = 0;
	return array($repute_dimond,$repute_shell);
}
?>
